﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Text;
using Kent.Boogaart.KBCsv;
using Newtonsoft.Json;

namespace Csv2Json
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 3 || (args.Length == 4 && args[3] != "min") || args.Length > 4)
            {
                string exe = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location);
                Console.WriteLine("Usage: {0} input.csv <delim> output.json [min]", exe);
                Console.WriteLine("delim is the delimiter used in the file");
                return;
            }

            using (var fileStream = File.OpenRead(args[0]))
            {
                var reader = new CsvReader(fileStream, Encoding.Default);
                reader.ValueSeparator = args[1][0];

                var objects = new List<ExpandoObject>();
                reader.ReadHeaderRecord();
                while (reader.HasMoreRecords)
                {
                    var record = reader.ReadDataRecord();

                    var data = new ExpandoObject();

                    var dictionary = (IDictionary<string, object>) data;

                    for (int i = 0; i < record.Count; i++)
                    {
                        dictionary[reader.HeaderRecord[i]] = record[i];
                    }

                    objects.Add(data);
                }


                var formatting = Formatting.Indented;

                if (args.Length > 3 && args[3] == "min")
                {
                    formatting = Formatting.None;
                }

                string jsonOfTest = JsonConvert.SerializeObject(objects, formatting);

                if (args[2] == "con")
                {
                    Console.WriteLine(jsonOfTest);
                }
                else
                {
                    File.WriteAllText(args[2], jsonOfTest);
                }
            }
        }
    }
}
